package com.codc;

import com.struct.Response;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.msgpack.MessagePack;

/**
 * Created by Greg.chen on 2016-03-20.
 */
public class ResponseEncoder extends MessageToByteEncoder<Response> {


    @Override
    protected void encode(ChannelHandlerContext ctx, Response response, ByteBuf sendBuf) throws Exception {
        if (response == null)
            throw new Exception("The response encode message is null");


        sendBuf.writeInt(response.getHeader().getCrcCode()); //校验码, 2个字节
        sendBuf.writeInt((response.getHeader().getLength()));
        sendBuf.writeInt(response.getHeader().getStateCode());

        byte[] uriBytes = response.getHeader().getUri().getBytes();
        sendBuf.writeInt(uriBytes.length);
        sendBuf.writeBytes(uriBytes);

        MessagePack msgpack = new MessagePack();
        if (response.getBody() != null) {
            byte[] raw = msgpack.write(response.getBody());
            sendBuf.writeBytes(raw);
        }
        else{
            sendBuf.writeByte(0);
        }

        sendBuf.setInt(4, sendBuf.readableBytes() -8);
    }
}
